/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.client.db.tasks;

import java.sql.SQLException;
import java.util.List;
import pl.cezary.butler.walili.client.DownloadTask;
import pl.cezary.butler.walili.client.DownloadTaskStatus;
import pl.cezary.butler.walili.server.db.tasks.FetchingTask;

/**
 *
 * @author Czarek
 */
public class FetchDownloadTasks extends FetchingTask<List<DownloadTask>> {
    
    private static int counter;
    private List<DownloadTask> result;
    private final  int limit;
    
    
    private final boolean fetchFailed;

    public FetchDownloadTasks(int limit) {
        this(limit,counter%10==0);
    }        

    public FetchDownloadTasks(int limit,boolean failed) {        
        this.limit = limit;
        this.fetchFailed = failed;
        ++counter;
    }

    public FetchDownloadTasks() {
        this(-1, counter%10==0);
    }
    
    

    @Override
    protected void executeInternal() throws SQLException {
        result = getJdbcTemplate().query("SELECT * FROM filesToDownload WHERE status=? ORDER BY status,id"+((limit>0)?" LIMIT "+limit:""),DownloadTask.getMapper(),(!fetchFailed)?DownloadTaskStatus.NEW.ordinal():DownloadTaskStatus.FAILURE.ordinal());                
    }

    @Override
    protected List<DownloadTask> $getResultsNonLocking() {
        return result;        
    }
    
}
